package com.oocl.xmlparser;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.oocl.messageproduce.MsgProducer;
import com.oocl.messageproduce.MessageProducerFactory;

public class MessageProduceHandler extends DefaultHandler{
	
	private MsgProducer producer;
	private JSONObject json ;
	private String type1 ="";
	
	
	public MessageProduceHandler(){
		producer = MessageProducerFactory.newInstance().createMsgProducer("bookQueue");
	}
	
	@Override
	public void startDocument() throws SAXException {
		
	}

	@Override
	public void endDocument() throws SAXException {
	
	}

	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		if(qName.equals("book")){
			json =new JSONObject();
		}
		else if(qName.equals("id")){
			type1=qName;
		}else if(qName.equals("name")){
			type1=qName;
		}
		else if(qName.equals("pubDate")){
			type1=qName;
		}
		else if(qName.equals("author")){
			type1=qName;
		}else if(qName.equals("price")){
			type1=qName;
		}else if(qName.equals("newBook")){
			type1=qName;
		}else if(qName.equals("publisher")){
			type1=qName;
		}
	}

	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		if(qName.equals("book")){
			producer.send(json.toString());
			json = null;
		}
		type1="";
	}

	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		String s = new String(ch, start, length);
		try {
			 if(type1.equals("id")){
				json.put("id", s);
			}else if(type1.equals("name")){
				json.put("name", s);
			}
			else if(type1.equals("pubDate")){
				json.put("pubDate", s);
			}
			else if(type1.equals("author")){
				json.put("author", s);
			}else if(type1.equals("price")){
				json.put("price", s);
			}else if(type1.equals("newBook")){
				json.put("newBook", s);
			}else if(type1.equals("publisher")){
				json.put("publisher", s);
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	
}
